package com.csc531.lists;

import java.util.ArrayList;

import android.app.ExpandableListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SimpleCursorAdapter;

import com.csc531.Manager;
import com.csc531.R;
import com.csc531.DataTypes.Course;
import com.csc531.DataTypes.Task;
import com.csc531.adapters.CoursesExpandableListAdapter;
import com.csc531.adapters.ManagerDbAdapter;
import com.csc531.edit.TasksEdit;
import com.csc531.settingsPanel.Settings;

/**
 * @author Javier Figueroa
 */
public class TaskListByCourses extends ExpandableListActivity 
{
	//logging
	private static final String TAG = "CLASSES TAB";

	//menu
	private static final int INSERT_ID = Menu.FIRST;
	private static final int EDIT_ID = Menu.FIRST + 1;
	private static final int DELETE_ID = Menu.FIRST + 2;
	private static final int SWITCH_TO_THINLIST = Menu.FIRST + 3;
	private static final int SETTINGS = Menu.FIRST + 4;


	//globals
	private ManagerDbAdapter _mDbHelper;
	private ArrayList<Object> _tasksDatabaseRowIds;
	private ArrayList<Course> _uniqueCourses;
	private CoursesExpandableListAdapter _classesTabAdapter;
	private SimpleCursorAdapter _simpleTaskCursor;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{
		super.onActivityResult(requestCode, resultCode, intent);
		fillTaskListData();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, SWITCH_TO_THINLIST, 0, R.string.menu_switch_to_thinlist);
		menu.add(0, INSERT_ID, 0, R.string.menu_insert);
		menu.add(0, EDIT_ID, 0, R.string.menu_edit);
		menu.add(0, DELETE_ID, 0,  R.string.menu_delete);
		menu.add(0, SETTINGS, 0, R.string.menu_config);

		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) 
	{
		switch(item.getItemId())
		{
		case INSERT_ID:
			createTask();
			return true;
		case EDIT_ID:
			editTask();
			return true;
		case DELETE_ID:
			deleteTask();
			fillTaskListData();
			return true;
		case SWITCH_TO_THINLIST:
			switchToViewAll();
			return true;
		case SETTINGS:
			settings();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}
	
	private void settings() 
	{
		Intent i = new Intent(this, Settings.class);
		startActivity(i);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		_mDbHelper = new ManagerDbAdapter(this);
		_mDbHelper.open();
		fillTaskListData();
	}

	private void fillTaskListData() 
	{
		initializeListAdapterRowIdsAndUniqueCourses();
		fetchTasksFromDatabase();

		try
		{
			printTasksToClassesTab();
		}
		catch(RuntimeException ex)
		{
			Log.v(TAG,"Error trying to print tasks to task list");
		}
		
		setTaskListAdapter();
	}

	private void initializeListAdapterRowIdsAndUniqueCourses()
	{
		_classesTabAdapter = new CoursesExpandableListAdapter(this);
		_tasksDatabaseRowIds = new ArrayList<Object>();
		_uniqueCourses = new ArrayList<Course>();
	}

	private void fetchTasksFromDatabase()
	{
		Cursor taskCursor = _mDbHelper.fetchAllTasks();
		startManagingCursor(taskCursor);

		String[] from = new String[]{ManagerDbAdapter.KEY_TITLE};
		int[] to = new int[]{R.id.text1};

		_simpleTaskCursor = new SimpleCursorAdapter(this, R.layout.notes_row, taskCursor, from, to);
	}

	private void printTasksToClassesTab() throws RuntimeException
	{
		_simpleTaskCursor.getCursor().moveToFirst();

		int numberOfRows = _simpleTaskCursor.getCursor().getCount();
		int numberOfColumns = _simpleTaskCursor.getCursor().getColumnCount();

		Log.v(TAG, "num of rows: "+numberOfRows);
		Log.v(TAG, "num of cols: "+numberOfColumns);

		for( int i = 0; i < numberOfRows ; i++ ) 
		{
			addTasksToCourse();
			_simpleTaskCursor.getCursor().moveToNext();
		}

		for(Course course : _uniqueCourses)
		{
			_classesTabAdapter.addCourse(course);
		}

		for(Course course: _classesTabAdapter.getCourses())
		{
			_tasksDatabaseRowIds.add(course);
			for(Task task: course.getTasks()) 
			{
				_tasksDatabaseRowIds.add(task);	
			}
		}	
	}
	
	private void setTaskListAdapter()
	{
		_classesTabAdapter.createCourseWithTasksList();
		setListAdapter(_classesTabAdapter);
		registerForContextMenu(getExpandableListView());
	}

	private void addTasksToCourse()
	{
		int k = 0;

		String rowId = _simpleTaskCursor.getCursor().getString(k++);

		String courseName = _simpleTaskCursor.getCursor().getString(k++);
		Course course = checkTheCourseIsUniqueForDisplay(courseName);

		course.setName(courseName);

		Task task = new Task();
		String title = _simpleTaskCursor.getCursor().getString(k++);

		String dueDate = _simpleTaskCursor.getCursor().getString(k++);
		task.setDate(dueDate);

		String description = _simpleTaskCursor.getCursor().getString(k++);
		task.setDescription(description);

		task.setTitle(
				title +
				" - (" + dueDate + ") - " +
				description
		);

		task.setCourseName(course.getName());
		task.setTaskId(Integer.parseInt(rowId));

		course.addTask(task);
		if(_uniqueCourses.contains(course) == false) 
		{
			_uniqueCourses.add(course);
		}
	}

	private Course checkTheCourseIsUniqueForDisplay(String courseName) 
	{
		Course course = new Course();
		for (Course aCourse : _uniqueCourses ) 
		{
			if(aCourse.getName().compareTo(courseName) == 0) 
			{
				course = aCourse;
			}
		}

		return course;
	}

	private void switchToViewAll() 
	{
		Intent i = new Intent(this, Manager.class);
		i.putExtra("TAB", Manager.CLASSES_TAB);
		i.putExtra("CLASSESVIEWTYPE", Manager.CLASSES_THINLIST);
		startActivity(i);
	}

	private void deleteTask() 
	{
		if(checkTasksExist() == false)
		{
			return;
		}
		try 
		{
			if(getExpandableListView().getSelectedView().isClickable())
			{
				_mDbHelper.deleteTask(getTaskIdRelatedToDisplay());
			}
		}
		catch(NullPointerException ex)
		{
			Log.v(TAG,ex.toString());
		}
	}

	private void editTask()
	{
		Intent i = new Intent(this, TasksEdit.class);

		if(checkTasksExist() == false) 
		{
			return;
		}

		try 
		{
			if(getExpandableListView().getSelectedView().isClickable())
			{

				long id = getTaskIdRelatedToDisplay();

				i.putExtra(ManagerDbAdapter.KEY_ROWID,id);
				startActivityForResult(i, TaskListByUpcoming.ACTIVITY_EDIT);
			}
		}
		catch(NullPointerException ex)
		{
			Log.v(TAG,ex.toString());
		}
	}

	private int getTaskIdRelatedToDisplay() 
	{
		Task selectedItem = (Task) getExpandableListView().getSelectedItem();
		int id = (int) getExpandableListView().getSelectedId();
		int relativeDisplayPositionToDatabaseRowIdsList = 0;

		for(int i = 0 ; i < _tasksDatabaseRowIds.size() ; i++ ) 
		{ 
			if(_tasksDatabaseRowIds.get(i) instanceof Course)
			{
				String courseNameSelectedItem = selectedItem.getCourseName();
				String courseNameFromArrayList = ((Course) _tasksDatabaseRowIds.get(i) ).getName();

				if(courseNameSelectedItem.compareTo(courseNameFromArrayList) == 0) {
					relativeDisplayPositionToDatabaseRowIdsList = i + id + 1;
				}
			}
		}
		selectedItem = (Task) _tasksDatabaseRowIds.get(relativeDisplayPositionToDatabaseRowIdsList);

		return selectedItem.getTaskId();
	}

	private void createTask() 
	{
		Intent i = new Intent(this, TasksEdit.class);
		startActivityForResult(i, TaskListByUpcoming.ACTIVITY_CREATE);
	}

	private boolean checkTasksExist() 
	{
		if(_tasksDatabaseRowIds.size() <= 0)
		{
			return false;
		}
		else 
		{
			return true;
		}
	}
}
